package com.xdemo.community.socketserver;


import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import com.xdemo.processor.IProcessor;
import com.xdemo.server.BaseServerMessage;
import com.xdemo.server.ServerSource;

public class CommunitySocketServerHandler extends SimpleChannelUpstreamHandler {
	
	public IProcessor<Integer> processor;
	
	public CommunitySocketServerHandler(IProcessor<Integer> processor) {
		this.processor = processor;
	}
	
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		if(!(e.getMessage() instanceof BaseServerMessage)) {
			return;
		}
		BaseServerMessage _msg = (BaseServerMessage)e.getMessage();
		if(ctx.getAttachment() == null) {
			ServerSource _server = new ServerSource();
			ctx.setAttachment(_server);
			_server.setContext(ctx);
		}
		_msg.setServer((ServerSource)ctx.getAttachment());
		processor.execute(_msg);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		
	}

	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		
	}

}
